<template>
  <base-layout>
    <div class="write-blog-container">
      <!-- 顶部操作栏 -->
      <div class="header-actions">
        <a-button class="back-btn" @click="handleBack">
          <template #icon><arrow-left-outlined /></template>
          返回
        </a-button>
        <div class="right-actions">
          <a-button @click="handleSaveDraft">保存草稿</a-button>
          <a-button type="primary" @click="handlePublish">发布文章</a-button>
        </div>
      </div>

      <div class="main-content">
        <!-- 左侧主编辑区 -->
        <div class="content-main">
          <div class="editor-card">
            <!-- 标题输入 -->
            <div class="title-section">
              <a-input
                v-model:value="blogData.title"
                placeholder="请输入文章标题"
                class="title-input"
                :maxLength="100"
                show-count
              />
            </div>

            <div class="divider"></div>

            <!-- Markdown编辑器 -->
            <div class="editor-section">
              <a-tabs v-model:activeKey="activeTab" class="editor-tabs">
                <a-tab-pane key="edit" tab="编辑">
                  <a-textarea
                    v-model:value="blogData.content"
                    placeholder="使用 Markdown 格式编写文章..."
                    :auto-size="{ minRows: 20, maxRows: 50 }"
                    @keydown.tab.prevent="handleTab"
                    class="content-editor"
                  />
                </a-tab-pane>
                <a-tab-pane key="preview" tab="预览">
                  <div class="markdown-preview" v-html="markdownPreview"></div>
                </a-tab-pane>
              </a-tabs>
            </div>
          </div>
        </div>

        <!-- 右侧设置区 -->
        <div class="content-side">
          <!-- 封面图片上传 -->
          <div class="side-card">
            <div class="section-title">封面图片</div>
            <div class="upload-area">
              <a-upload
                v-model:file-list="fileList"
                list-type="picture-card"
                :show-upload-list="true"
                :before-upload="beforeUpload"
                :customRequest="handleCustomUpload"
                :maxCount="1"
                accept="image/*"
              >
                <div v-if="fileList.length < 1">
                  <plus-outlined />
                  <div style="margin-top: 8px">上传封面</div>
                </div>
              </a-upload>
              <div class="upload-tip">建议尺寸：1200x675px，格式：jpg、png，大小：≤5MB</div>
            </div>
          </div>

          <!-- 文章分类和标签 -->
          <div class="side-card">
            <div class="section-title">分类和标签</div>
            <div class="meta-inputs">
              <a-select
                v-model:value="blogData.category"
                placeholder="选择分类"
                class="category-select"
              >
                <a-select-option value="tech">技术</a-select-option>
                <a-select-option value="project">项目</a-select-option>
                <a-select-option value="experience">经验分享</a-select-option>
                <a-select-option value="other">其他</a-select-option>
              </a-select>

              <div class="tags-wrapper">
                <a-select
                  v-model:value="blogData.tags"
                  mode="tags"
                  placeholder="添加标签，用分号(;)分隔"
                  class="tags-select"
                  :token-separators="[';']"
                />
                <div class="tags-tip">按 Enter 或分号(;)添加标签</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </base-layout>
</template>

<script>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import BaseLayout from '@/components/layout/BaseLayout.vue'
import { message } from 'ant-design-vue'
import {
  ArrowLeftOutlined,
  PlusOutlined
} from '@ant-design/icons-vue'
import { marked } from 'marked'

// 配置 marked
marked.setOptions({
  breaks: true,  // 支持 GitHub 风格的换行符
  gfm: true,     // 启用 GitHub 风格的 Markdown
  headerIds: false // 禁用标题 ID
})

export default {
  name: 'WriteBlog',
  components: {
    BaseLayout,
    ArrowLeftOutlined,
    PlusOutlined
  },
  setup() {
    const router = useRouter()
    const activeTab = ref('edit')
    const fileList = ref([])

    const blogData = reactive({
      title: '',
      cover: '',
      category: undefined,
      tags: [],
      content: ''
    })

    // 返回上一页
    const handleBack = () => {
      router.back()
    }

    // 保存草稿
    const handleSaveDraft = () => {
      // TODO: 实现保存草稿功能
      message.success('草稿已保存')
    }

    // 发布文章
    const handlePublish = () => {
      if (!blogData.title.trim()) {
        message.error('请输入文章标题')
        return
      }
      if (!blogData.content.trim()) {
        message.error('请输入文章内容')
        return
      }
      if (!blogData.category) {
        message.error('请选择文章分类')
        return
      }

      // TODO: 实现发布文章功能
      message.success('文章发布成功')
      router.push('/blog')
    }

    // 处理Tab键
    const handleTab = (e) => {
      const start = e.target.selectionStart
      const end = e.target.selectionEnd
      blogData.content = blogData.content.substring(0, start) + '    ' + blogData.content.substring(end)
      // 设置光标位置
      setTimeout(() => {
        e.target.selectionStart = e.target.selectionEnd = start + 4
      })
    }

    // 自定义上传方法
    const handleCustomUpload = async ({ file, onSuccess, onError }) => {
      try {
        // 这里暂时使用本地预览，后续可以改为真实的上传接口
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => {
          const url = reader.result
          blogData.cover = url
          fileList.value = [
            {
              uid: Date.now().toString(),
              name: file.name,
              status: 'done',
              url: url,
              thumbUrl: url
            }
          ]
          onSuccess({ url })
        }
        reader.onerror = () => {
          onError(new Error('文件读取失败'))
          message.error('文件读取失败')
        }
      } catch (error) {
        onError(error)
        message.error('上传失败')
      }
    }

    // 修改处理上传前的验证
    const beforeUpload = (file) => {
      const isImage = file.type.startsWith('image/')
      if (!isImage) {
        message.error('只能上传图片文件！')
        return false
      }
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        message.error('图片大小不能超过 5MB！')
        return false
      }
      return true
    }

    // Markdown预览
    const markdownPreview = computed(() => {
      return marked(blogData.content)
    })

    return {
      activeTab,
      blogData,
      fileList,
      handleBack,
      handleSaveDraft,
      handlePublish,
      handleTab,
      handleCustomUpload,
      beforeUpload,
      markdownPreview
    }
  }
}
</script>

<style scoped>
.write-blog-container {
  min-height: calc(100vh - 104px);
  padding: 24px;
  background: #f0f2f5;
  margin: 0;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 64px;
  padding: 0 24px;
  margin-bottom: 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.right-actions {
  display: flex;
  gap: 12px;
}

.main-content {
  display: flex;
  gap: 24px;
  margin-bottom: 24px;
}

.content-main {
  flex: 1;
  min-width: 0;
  max-width: calc(100% - 384px);
}

.content-side {
  width: 360px;
  flex-shrink: 0;
}

.editor-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;
  min-height: calc(100vh - 240px);
}

.title-section {
  padding: 24px 24px 0;
}

.title-input {
  border: none;
  padding: 0;
  margin-bottom: 0;
  box-shadow: none;
  background: transparent;
}

.title-input :deep(.ant-input) {
  font-size: 28px;
  font-weight: 500;
  border: none;
  padding: 0;
}

.title-input :deep(.ant-input:focus) {
  box-shadow: none;
}

.title-input :deep(.ant-input-show-count-suffix) {
  margin-top: 8px;
  color: rgba(0, 0, 0, 0.45);
}

.divider {
  height: 1px;
  background: #f0f0f0;
  margin: 24px;
}

.editor-section {
  padding: 0 24px 24px;
  height: calc(100% - 120px);
}

.editor-tabs {
  height: 100%;
}

.editor-tabs :deep(.ant-tabs-content) {
  height: calc(100% - 44px);
}

.editor-tabs :deep(.ant-tabs-tabpane) {
  height: 100%;
}

.content-editor {
  border: none;
  resize: none;
  font-family: "Menlo", "Monaco", "Consolas", monospace;
  padding: 0;
  margin-top: 16px;
  height: calc(100% - 16px) !important;
  font-size: 16px;
  line-height: 1.6;
}

.content-editor:focus {
  box-shadow: none;
}

.markdown-preview {
  height: calc(100% - 16px);
  padding: 24px;
  margin-top: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  background: #fafafa;
  overflow-y: auto;
  font-size: 16px;
  line-height: 1.6;
}

.side-card {
  padding: 0;
  margin-bottom: 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.section-title {
  padding: 16px 24px;
  font-size: 16px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
  border-bottom: 1px solid #f0f0f0;
}

.upload-area {
  padding: 24px;
}

:deep(.ant-upload-list) {
  width: 100%;
}

:deep(.ant-upload-list-picture-card-container),
:deep(.ant-upload.ant-upload-select) {
  width: 100% !important;
  height: 180px !important;
  margin: 0;
}

:deep(.ant-upload-list-item-image) {
  object-fit: cover !important;
}

:deep(.ant-upload-list-picture-card .ant-upload-list-item) {
  padding: 0;
}

:deep(.ant-upload-list-picture-card .ant-upload-list-item-thumbnail) {
  opacity: 1;
}

:deep(.ant-upload-list-picture-card .ant-upload-list-item-thumbnail img) {
  object-fit: cover;
}

.upload-tip {
  margin-top: 8px;
  color: rgba(0, 0, 0, 0.45);
  font-size: 12px;
}

.meta-inputs {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 24px;
}

.category-select,
.tags-select {
  width: 100%;
}

:deep(.ant-tabs-nav) {
  margin-bottom: 16px;
  padding: 0 24px;
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.ant-input-textarea-show-count::after) {
  margin-top: 4px;
  color: rgba(0, 0, 0, 0.45);
}

.tags-wrapper {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.tags-tip {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
  margin-top: 4px;
}
</style> 